package com.wuster.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.wuster.config.OSSConfig;
import com.wuster.constant.FileConstant;
import com.wuster.exception.CategoryException;
import com.wuster.result.ResultCodeEnum;
import com.wuster.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


/**
 * ClassName: FileServiceImpl
 * Package: com.wuster.service.impl
 * Description: TODO
 *
 * @Author VictoriaZhou
 * @Create 2024/7/4 13:19
 * @Version 1.0
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OSSConfig ossConfig;

    @Override
    public String upload(MultipartFile file) throws IOException {
        //file == null 用于检查是否传递了文件，而 file.isEmpty() 用于检查传递的文件是否有内容。
//        if (file == null || file.isEmpty()) {
//            throw new CategoryException(ResultCodeEnum.FILE_IMAGE_EMPTY);
//        }

        // 检查文件大小是否超过限制
//        log.info("前端传来的文件size是{}",file.getSize() );
//        if (file.getSize() > FileConstant.MAX_FILE_SIZE) {
//            throw new CategoryException(ResultCodeEnum.FILE_IMAGE_LIMIT_SIZE);
//        }

        String contentType = file.getContentType();
        log.info("前端传来的文件类型是{}",contentType);
        // 检查文件类型是否是图片
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new CategoryException(ResultCodeEnum.FILE_ONLY_IMAGE);
        }
        // 检查文件类型是否是允许的图片格式
        if (!FileConstant.ALLOWED_FILE_TYPES.contains(contentType)) {
            throw new CategoryException(ResultCodeEnum.FILE_IMAGE_LIMIT_TYPE);
        }

        //获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        //获取原生文件名
        String originalFilename = file.getOriginalFilename();

        //JDK11的日期格式
        LocalDateTime time = LocalDateTime.now();
        DateTimeFormatter dft = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        //拼装OSS上存储的路径
        String folder = dft.format(time);
        String fileName = generateUUID();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        //在OSS上bucket下的文件名
        String uploadFileName = "user/" + folder + "/" + fileName + extension;

        // 设置对象元数据
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(getContentType(extension)); // 根据文件扩展名设置 MIME 类型
        metadata.setContentDisposition("inline"); // 确保文件在浏览器中展示

        PutObjectResult result = ossClient
                .putObject(bucketName
                        , uploadFileName
                        , file.getInputStream()
                        ,metadata);
        //拼装返回路径
        if (result != null) {
            return "https://" + bucketName + "." + endPoint + "/" + uploadFileName;
        }

        //OSS关闭服务，不然会造成OOM
        ossClient.shutdown();
        return null;
    }
    /**
     * 根据文件扩展名获取 MIME 类型
     *
     * @param extension 文件扩展名
     * @return MIME 类型
     */
    private String getContentType(String extension) {
        if (extension.equalsIgnoreCase(".jpg") || extension.equalsIgnoreCase(".jpeg")) {
            return "image/jpeg";
        } else if (extension.equalsIgnoreCase(".png")) {
            return "image/png";
        } else if (extension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        // 可以根据需要添加更多类型
        return "application/octet-stream";
    }
    /**
     * 获取随机字符串
     *
     * @return
     */
    private String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }


}
